var ByteBuffer = window.dcodeIO.ByteBuffer;
var websockets = [];
var reconnInterval = 10;    //重连间隔
var reconnLock = false;      //避免重复连接
var needconn = true;      //是否需要重连
var lastInteractionTime = 0;//上一次交互时间
var heartbeatTimeout = 60 * 1000;
var heartbeatSendInterval = heartbeatTimeout / 2;
var Command;
var stat = {
	received : 0  //收到次数
	,sent:0       //发送次数
	,connCount:0  //连成功次数
	,reconnCount:0 //重连次数
};

protobuf.load("/chat.proto", function(err, root) {
	if (err) {
		throw err;
	}
	loadClass(root);
});

function loadClass(root) {
	ChatReqBody = root.lookup("com.tianpengtech.im.common.pockets.ChatReqBody");
	ChatRespBody = root.lookup("com.tianpengtech.im.common.pockets.ChatRespBody");
	ChatType = root.lookup("com.tianpengtech.im.common.pockets.ChatType");
	Command = root.lookup("com.tianpengtech.im.common.pockets.Command");
}

function initWs(url) {
	try {
		var ws = new WebSocket(url);
		ws.binaryType = 'arraybuffer'; // 'blob';//
		initWsEvent(ws, url);
		return ws;
	} catch (e) {
		console.log(e);
		reconn(url, null, e);
	}
}

function initWsEvent(ws, url){
	ws.onopen = function(event) {
		
		var ws = event.srcElement;
		
		stat.connCount++;
		websockets.push(ws);
		lastInteractionTime = new Date().getTime();
		
		var command = Command.values.COMMAND_SYS_MESSAGE_REQ;
		var bodyData = {
			type : ChatType.CHAT_TYPE_PUBLIC,
			text:"helloWorld",
			group:"sys",
			toId:"2367"
		};
		sendPacket(ws, command, ChatReqBody, bodyData);
	};

	ws.onmessage = function(event) {
		var ws = event.srcElement;
		stat.received++;
		var arrayBuffer = event.data;
		
		var byteBuffer = ByteBuffer.wrap(arrayBuffer);
		var command =  Command.valuesById[byteBuffer.readByte()];
		arrayBuffer = byteBuffer.toArrayBuffer();
		byteBuffer = ByteBuffer.wrap(arrayBuffer);
		
		var uint8Array = new Uint8Array(arrayBuffer);
		handler[command].call(handler[command], uint8Array, event, ws);
		
		lastInteractionTime = new Date().getTime();
	};

	ws.onclose = function(event) {
		var ws = event.srcElement;		
		reconn(url, event, null);
	};

	ws.onerror = function(event){
		var ws = event.srcElement;
		reconn(url, event, null)
	};
}


function reconn(url, event, e) {
	if (!needconn) {
		console.log("已经不需要重连了", event, e);
		return;
	}
	
	if (reconnLock) {
		console.log("没有拿到重连权限", event, e);
		return;
	}
	
	reconnLock = true;
	stat.reconnCount++;

	setTimeout(function() {
				initWs(url);
				reconnLock = false;
			}, reconnInterval);
}


function sendPacket(ws, command, BodyClass, bodyData) {
    var bodyObj = null;
    if (bodyData) {
    	bodyObj = BodyClass.create(bodyData);
    }
    
    var bodyBuffer = null;
    if (bodyObj) {
    	bodyBuffer = BodyClass.encode(bodyObj).finish();
    }
	
	sendBuffer(ws, command, bodyBuffer);
}

function sendBuffer(ws, command, bodyBuffer){
	var bodyLength = 0;
	if (bodyBuffer) {
		bodyLength = bodyBuffer.length;
	}

	var allBuffer = ByteBuffer.allocate(1 + bodyLength);
	allBuffer.writeByte(command);

	if (bodyBuffer) {
		allBuffer.append(bodyBuffer);
	}
	ws.send(allBuffer.buffer);
	lastInteractionTime = new Date().getTime();
}


function ping()
{
	var nowTime = new Date().getTime();
	var iv = nowTime - lastInteractionTime; // 已经多久没发消息了
	if ((heartbeatSendInterval + iv) >= heartbeatTimeout) {
		var command = Command.values.COMMAND_HEARTBEAT_REQ;
		for(var i = 0; i < websockets.length; i++){
			var ws = websockets[i];
			sendBuffer(ws, command, null);
		}
	}
}
setInterval("ping()", heartbeatSendInterval);


/**
 * 消息处理者
 * @type 
 */
var handler = {};
handler.COMMAND_SYS_MESSAGE_RESP = function(uint8Array, event, ws){
	var respBody = ChatRespBody.decode(uint8Array);
	//chat.chatRespBodys.push(respBody.text);
	$("#content").html(respBody.text);
	$("#msgTime").html(respBody.time)
};



//var chat = new Vue({
//	  el: '#chat',
//	  data: {
//	    chatRespBodys:[]
//	  }
//	});


function connectionConfig(){
	var server = "106.14.177.36";
	var port= "9322";
	var wsUrl = "ws://" + server+ ":" + port;
	initWs(wsUrl);
}